<?php

App::uses('CrudController', 'Controller');

class TestRegisterController extends CrudController {
    public $_model = 'UserTest';
    
    public function admin() {
        $this->request->allowMethod('get');
        $this->loadModel('LogAddressUser');
        $appBosch = new stdClass();
        $appBosch->owner = $this->Auth->user('id');
        $appBosch->address = $this->LogAddressUser->getLastAddress($this->Auth->user('id'));
        $this->set('appBosch', $appBosch);
        $this->set('title', __('Cursos'));
        $this->set('description', 'Registro a cursos');
    }

    public function registered()
    {
        $this->request->allowMethod('get');
        $appBosch = new stdClass();
        $this->set('appBosch', $appBosch);
        $this->set('title', __('Cursos'));
        $this->set('description', 'Registro de cursos');
    }

    public function getUsersForTest($scheduleId)
    {
        $this->request->allowMethod('get');
        $m = $this->_model;
        $this->loadModel($m);
        $records = $this->$m->getEnabledByTest($scheduleId);
        $this->set(array('records' => $records, '_serialize' => 'records'));
        $this->viewClass = 'Json';
    }

    public function registerUsers() {
        $this->request->allowMethod('get');
        $params = $this->request->query;
        $invalid = array();
        $response = false;
        if (isset($params['scheduleId']) && isset($params['userIds'])) {
            $scheduleId = $params['scheduleId'];
            $m = $this->_model;
            $this->loadModel('User');
            $this->loadModel('Schedule');
            $this->loadModel($m);
            $schedule = $this->Schedule->findById($scheduleId);
            $cupo = intval($schedule['Schedule']['room_capacity']) - intval($schedule['Schedule']['users_registered']);
            $nominas = explode(' ', $params['userIds']);
            foreach ($nominas as $nom) {
                $n = trim($nom);
                $us = $this->User->findByNominaAndStatus($n, User::STATUS_ENABLED);
                if (isset($us['User'])) {
                    if($us['User']['category_id'] == Category::ASOCIADO) {
                        $usi = $this->$m->findByUserIdAndScheduleIdAndStatus($us['User']['id'], $scheduleId, UserTest::STATUS_ENABLED);
                        if (!isset($usi[$m])) {
                            if ($cupo > 0) {
                                $ut = array(
                                    'user_id' => $us['User']['id'],
                                    'schedule_id' => $scheduleId
                                );
                                $this->$m->save($ut);
                                $this->$m->clear();
                                $cupo--;
                            } else {
                                $invalid[] = array('nomina' => $n, 'message' => __('Ya no hay cupo'));
                            }
                        } else {
                            $invalid[] = array('nomina' => $n, 'message' => __('Ya esta inscrito'));
                        }
                    } else {
                        $invalid[] = array('nomina' => $n, 'message' => __('No es un asociado'));
                    }
                } else {
                    $invalid[] = array('nomina' => $n, 'message' => __('No es un usuario valido'));
                }
            }
            $response = $invalid;
        }

        $this->set(array('records' => $response, '_serialize' => 'records'));
        $this->viewClass = 'Json';
    }

    public function unscribeAll($scheduleId, $testId)
    {
        $m = $this->_model;
        $this->loadModel($m);
        $this->loadModel('Evaluation');
        $this->loadModel('EvaluationDetail');
        $this->loadModel('Attempt');
        $this->loadModel('Test');
        $resp = '';
        try {
            $test = $this->Test->findById($testId);
            $userTests = $this->$m->findAllByScheduleIdAndStatus($scheduleId, UserTest::STATUS_ENABLED);
            foreach($userTests as &$userTest) {
                $userTest = $userTest[$m];
                $userTest['status'] = UserTest::STATUS_DISABLED;
                $att = $this->Attempt->getAttemptByUserTest($userTest['id']);
                if (isset($att['Attempt']) === true) {
                    $att['Attempt']['status'] = Attempt::STATUS_DISABLED;
                    $this->Attempt->save($att);
                    $this->Attempt->clear();
                    $cant = $this->Attempt->getCountAttempts($att['Attempt']['evaluation_id']);
                    $eval = $this->Evaluation->findByIdAndStatus($att['Attempt']['evaluation_id'], Evaluation::STATUS_ENABLED);
                    if (count($eval) > 0) {
                        $eds = $this->EvaluationDetail->findAllByEvaluationIdAndStatus($att['Attempt']['evaluation_id'], EvaluationDetail::STATUS_ENABLED);
                        $eval['Evaluation']['attempts'] = $cant[0]['cant'];
                        if (intval($cant[0]['cant']) > 0) {
                            $lastA = $this->Attempt->getLastAttempt($att['Attempt']['evaluation_id']);
                            $calThemes = floatval($test['Test']['minimum_qualification']) >= floatval($lastA[0]['qualification']) ? 0 : 100;
                            foreach ($eds as &$ed) {
                                $ed['EvaluationDetail']['qualification'] = floatval($calThemes);
                            }
                        } else {
                            $eval['Evaluation']['status'] = Evaluation::STATUS_DISABLED;
                            foreach ($eds as &$ed) {
                                $ed['EvaluationDetail']['status'] = EvaluationDetail::STATUS_DISABLED;
                            }
                        }
                        $this->EvaluationDetail->saveMany($eds);
                        $this->Evaluation->save($eval);
                        $this->Evaluation->clear();
                    }
                }
            }
            /**
             * Guardamos todos los alumnos del curso que ya fueron dados de baja
             * del curso
             */
            $this->$m->saveMany($userTests);
        } catch (PDOException $e) {
            $resp = array('message' => $e->getMessage());
        }
        $this->set(array('records' => $resp, '_serialize' => 'records'));
        $this->viewClass = 'Json';
    }

    protected function getRecords($param)
    {
        $m = $this->_model;
        $records = $this->$m->getEnabledByUser($this->Auth->user('id'));
        return $records;
    }

    protected function c($model)
    {
        return array(
            'user_id' => $this->Auth->user('id'),
            'schedule_id' => $model->value
        );
    }

    protected function u($model)
    {
        return array();
    }

    protected function id($model)
    {
        return $model->id;
    }

    protected function afterDestroy(&$destroyedModel) {
        $this->loadModel('TransportUser');
        $this->TransportUser->destroyRequest($destroyedModel['schedule_id'], $destroyedModel['user_id']);
    }

    public function destroyMasive() {
        $m = $this->_model;
        $this->loadModel($m);
        $this->loadModel('Schedule');
        $this->loadModel('Evaluation');
        $this->loadModel('EvaluationDetail');
        $this->loadModel('Attempt');
        $this->loadModel('Test');
        $resp = '';
        $uts = $this->request->query('ids');
        $testId = $this->request->query('testId');
        try {
            $test = $this->Test->findById($testId);
            foreach($uts as $ut) {
                $att = $this->Attempt->getAttemptByUserTest($ut);
                if (isset($att['Attempt']) != false) {
                    $att['Attempt']['status'] = 0;
                    $this->Attempt->save($att);
                    $this->Attempt->clear();
                    $cant = $this->Attempt->getCountAttempts($att['Attempt']['evaluation_id']);
                    $eval = $this->Evaluation->findByIdAndStatus($att['Attempt']['evaluation_id'], Evaluation::STATUS_ENABLED);
                    if (count($eval) > 0) {
                        $eds = $this->EvaluationDetail->findAllByEvaluationIdAndStatus($att['Attempt']['evaluation_id'], EvaluationDetail::STATUS_ENABLED);
                        $eval['Evaluation']['attempts'] = $cant[0]['cant'];
                        if (intval($cant[0]['cant']) > 0) {
                            $lastA = $this->Attempt->getLastAttempt($att['Attempt']['evaluation_id']);
                            $calThemes = floatval($test['Test']['minimum_qualification']) >= floatval($lastA[0]['qualification']) ? 0 : 100;
                            foreach ($eds as &$ed) {
                                $ed['EvaluationDetail']['qualification'] = floatval($calThemes);
                            }
                        } else {
                            $eval['Evaluation']['status'] = Evaluation::STATUS_DISABLED;
                            foreach ($eds as &$ed) {
                                $ed['EvaluationDetail']['status'] = EvaluationDetail::STATUS_DISABLED;
                            }
                        }
                        $this->EvaluationDetail->saveMany($eds);
                        $this->Evaluation->save($eval);
                        $this->Evaluation->clear();
                    }
                }
                $reg = $this->$m->findById($ut);
                $reg[$m]['status'] = 0;
                $this->$m->save($reg);
                $this->$m->clear();
            }
        } catch (PDOException $e) {
            var_dump($e->getMessage());
        }
        $this->set(array('records' => $resp, '_serialize' => 'records'));
        $this->viewClass = 'Json';
    }

    public function createUserTransport($scheduleId) {
        $this->request->onlyAllow('post');
        $data = $this->request->data;
        if ($data['req'] == '1') {
            $this->loadModel('TransportRequest');
            $this->loadModel('TransportUser');
            $this->loadModel('LogAddressUser');
            $tr = $this->TransportRequest->findByScheduleId($scheduleId);
            $ut = array(
                'transport_request_id' => $tr['TransportRequest']['id'],
                'user_id' => $this->Auth->user('id'),
                'street' => $data['street'],
                'number' => $data['number'],
                'colony' => $data['colony'],
                'between_streets' => $data['between_streets']
            );
            $lau = array(
                'user_id' => $this->Auth->user('id'),
                'street' => $data['street'],
                'number' => $data['number'],
                'colony' => $data['colony'],
                'between_streets' => $data['between_streets']
            );
            $resp = $this->TransportUser->save($ut);
            $this->LogAddressUser->save($lau);
        } else {
            $resp = true;
        }
        $this->set(array('records' => $resp, '_serialize' => 'records'));
        $this->viewClass = 'Json';
    }
}
